﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using iemtm.WeChat.Core.Model;
using iemtm.WeChat.Core.Util;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iemtm.WeChat.Core.Quartz.Job
{
    /// <summary>
    /// 微信推送指标通报
    /// </summary>
    /// 
    [DisallowConcurrentExecution]//前一次任务未执行完成时不触发下次任务
    public class WxPushInformation : IJob
    {
        

        /// <summary>  
        /// 得到本周第一天(以星期一为第一天)  
        /// </summary>  
        /// <param name="datetime"></param>  
        /// <returns></returns>  
        public DateTime GetWeekFirstDayMon(DateTime datetime)
        {
            //星期一为第一天  
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);

            //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;

            //本周第一天  
            string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(FirstDay);
        }

        /// <summary>  
        /// 得到本周最后一天(以星期天为最后一天)  
        /// </summary>  
        /// <param name="datetime"></param>  
        /// <returns></returns>  
        public DateTime GetWeekLastDaySun(DateTime datetime)
        {
            //星期天为最后一天  
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);
            weeknow = (weeknow == 0 ? 7 : weeknow);
            int daydiff = (7 - weeknow);

            //本周最后一天  
            string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(LastDay);
        }

        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() =>
            {
                try
                {
                    if (DateTime.Now.Hour == 9 || DateTime.Now.Hour == 21)//早九点晚九点推送
                    {
                        if ((DateTime.Now.Minute == 0) && (DateTime.Now.Second >= 5 && DateTime.Now.Second < 10))//整点推送
                        //if(DateTime.Now.Minute%1==0&& (DateTime.Now.Second >= 5 && DateTime.Now.Second < 10))//测试时间 2分钟
                        {
                            Db.GetRepository<Log>().Insert(new Log() { LogName = "推送指标通报成功", LogDetails = "成功", CreateTime = DateTime.Now });

                            var userList = Db.GetRepository<UserAccount>().Where(c => c.WxOpenId != null && c.WxOpenId != "").ToList();//只获取已经绑定微信的帐号
                                    
                            foreach (var item in userList)
                            {
                                Task.Run(() =>
                                {
                                    var userAreaCode = Db.GetRepository<Company>().First(c => c.CompanyCode == item.CompanyCode).AreaCode;//获取账号AreaCode

                                    #region 日期处理
                                    var startTimeByDaily = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy/MM/dd") + " 00:00:00";
                                    var stopTimeByDaily = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy/MM/dd") + " 23:59:59";
                                    var startTimeByWeek = GetWeekFirstDayMon(Convert.ToDateTime(DateTime.Now.ToString())).ToString("yyyy/MM/dd") + " 00:00:00";
                                    var stopTimeByWeek = GetWeekLastDaySun(Convert.ToDateTime(DateTime.Now.ToString())).ToString("yyyy/MM/dd") + " 23:59:59";
                                    var startTimeByMon = Convert.ToDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("yyyy/MM/dd")).ToString("yyyy/MM") + "/01 00:00:00";
                                    var stopTimeByMon = Convert.ToDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("yyyy/MM/dd")).ToString("yyyy/MM/dd") + " 23:59:59";
                                    #endregion

                                    #region 日报
                                    //日总共单数量
                                    var AllAnnouceCountByDaily = 0;
                                    DataTable AllAnnouceCountByDailyDt = ($"SELECT COUNT(AnnounceId) AS Count FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND CreateDate BETWEEN '{startTimeByDaily}' AND '{stopTimeByDaily}'").SqlQuery();
                                    if (AllAnnouceCountByDailyDt == null)
                                        AllAnnouceCountByDaily = 0;
                                    else
                                        AllAnnouceCountByDaily = Convert.ToInt32(AllAnnouceCountByDailyDt.Rows[0]["Count"]);
                                    //日已完成工单数量
                                    var FiAnnnouceCountByDaily = 0;
                                    DataTable FiAnnnouceCountByDailyDt =($"SELECT AnnounceCode FROM dbo.AnnounceGen WHERE AnnounceCode IN (SELECT AnnounceCode FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND CreateDate BETWEEN '{startTimeByDaily}' AND '{stopTimeByDaily}' ) GROUP BY AnnounceCode").SqlQuery();
                                    if (FiAnnnouceCountByDailyDt == null)
                                        FiAnnnouceCountByDaily = 0;
                                    else
                                        FiAnnnouceCountByDaily = FiAnnnouceCountByDailyDt.Rows.Count;
                                    //日未接工单数量
                                    var noExtAnnouceCountByDaily = 0;
                                    DataTable noExtAnnouceCountByDailyDt = ($"SELECT COUNT(AnnounceId) AS Count FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND	 AnnounceStatus=20 AND CreateDate BETWEEN '{startTimeByDaily}' AND '{stopTimeByDaily}'").SqlQuery();
                                    if (noExtAnnouceCountByDailyDt == null)
                                        noExtAnnouceCountByDaily = 0;
                                    else
                                        noExtAnnouceCountByDaily = Convert.ToInt32(noExtAnnouceCountByDailyDt.Rows[0]["Count"]);
                                    #endregion

                                    #region 周报
                                    //周总共单数量
                                    var AllAnnouceCountByWeek = 0;
                                    DataTable AllAnnouceCountByWeekDt = ($"SELECT COUNT(AnnounceId) AS Count FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND CreateDate BETWEEN '{startTimeByWeek}' AND '{stopTimeByWeek}'").SqlQuery();
                                    if (AllAnnouceCountByWeekDt == null)
                                        AllAnnouceCountByWeek = 0;
                                    else
                                        AllAnnouceCountByWeek = Convert.ToInt32(AllAnnouceCountByWeekDt.Rows[0]["Count"]);
                                    //周已完成工单数量
                                    var FiAnnnouceCountByWeek = 0;
                                    DataTable FiAnnnouceCountByWeekDt = ($"SELECT AnnounceCode FROM dbo.AnnounceGen WHERE AnnounceCode IN (SELECT AnnounceCode FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND CreateDate BETWEEN '{startTimeByWeek}' AND '{stopTimeByWeek}' ) GROUP BY AnnounceCode").SqlQuery();
                                    if (FiAnnnouceCountByWeekDt == null)
                                        FiAnnnouceCountByWeek = 0;
                                    else
                                        FiAnnnouceCountByWeek = FiAnnnouceCountByWeekDt.Rows.Count;
                                    //周未接工单数量
                                    var noExtAnnouceCountByWeek = 0;
                                    DataTable noExtAnnouceCountByWeekDt = ($"SELECT COUNT(AnnounceId) AS Count FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND	 AnnounceStatus=20 AND CreateDate BETWEEN '{startTimeByWeek}' AND '{stopTimeByWeek}'").SqlQuery();
                                    if (noExtAnnouceCountByWeekDt == null)
                                        noExtAnnouceCountByDaily = 0;
                                    else
                                        noExtAnnouceCountByWeek = Convert.ToInt32(noExtAnnouceCountByWeekDt.Rows[0]["Count"]);
                                    #endregion

                                    #region 月报
                                    //月总共单数量
                                    var AllAnnouceCountByMon = 0;
                                    DataTable AllAnnouceCountByMonDt = ($"SELECT COUNT(AnnounceId) AS Count FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND CreateDate BETWEEN '{startTimeByMon}' AND '{stopTimeByMon}'").SqlQuery();
                                    if (AllAnnouceCountByMonDt == null)
                                        AllAnnouceCountByMon = 0;
                                    else
                                        AllAnnouceCountByMon = Convert.ToInt32(AllAnnouceCountByMonDt.Rows[0]["Count"]);
                                    //月已完成工单数量
                                    var FiAnnnouceCountByMon = 0;
                                    DataTable FiAnnnouceCountByMonDt = ($"SELECT AnnounceCode FROM dbo.AnnounceGen WHERE AnnounceCode IN (SELECT AnnounceCode FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND CreateDate BETWEEN '{startTimeByMon}' AND '{stopTimeByMon}' ) GROUP BY AnnounceCode").SqlQuery();
                                    if (FiAnnnouceCountByMonDt == null)
                                        FiAnnnouceCountByMon = 0;
                                    else
                                        FiAnnnouceCountByMon = FiAnnnouceCountByMonDt.Rows.Count;
                                    //月未接工单数量
                                    var noExtAnnouceCountByMon = 0;
                                    DataTable noExtAnnouceCountByMonDt = ($"SELECT COUNT(AnnounceId) AS Count FROM dbo.AnnounceList WHERE AreaCode LIKE '{userAreaCode}%' AND	 AnnounceStatus=20 AND CreateDate BETWEEN '{startTimeByMon}' AND '{stopTimeByMon}'").SqlQuery();
                                    if (noExtAnnouceCountByMonDt == null)
                                        noExtAnnouceCountByMon = 0;
                                    else
                                        noExtAnnouceCountByMon = Convert.ToInt32(noExtAnnouceCountByMonDt.Rows[0]["Count"]);
                                    #endregion

                                    //执行推送方法
                                    WeiXinPush.SendInformataionMsg(item.UserCode,
                                        new AnnouceCountByWxPushModel
                                        {
                                            AllAnnouceCountByDaily = AllAnnouceCountByDaily,//日总共单数量
                                            FiAnnnouceCountByDaily = FiAnnnouceCountByDaily,//日已完成工单数量
                                            noExtAnnouceCountByDaily = noExtAnnouceCountByDaily,//日未接工单数量
                                            AllAnnouceCountByWeek = AllAnnouceCountByWeek,//周总工单数量
                                            FiAnnnouceCountByWeek = FiAnnnouceCountByWeek,//周已完成工单数量
                                            noExtAnnouceCountByWeek = noExtAnnouceCountByWeek,//周未接工单数量,
                                            AllAnnouceCountByMon = AllAnnouceCountByMon,//月总工单数量
                                            FiAnnnouceCountByMon = FiAnnnouceCountByMon,//月已完成工单数量
                                            noExtAnnouceCountByMon = noExtAnnouceCountByMon,//月未接工单数量
                                        });
                                });
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Db.GetRepository<Log>().Insert(new Log() { LogName = "推送指标通报失败", LogDetails = e.ToString(), CreateTime = DateTime.Now });
                }
            });
        }
    }
}
